package celiasoft.itasalib.filegatherer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;

import android.util.Log;

public class FileHTTPFetcher {

	private static final String TAG = "itasalib.FileHTTPFetcher";
	
	private static final int COPY_BUFFER_SIZE = 4096;
	
	public static byte[] fetch(URL remoteUrl) throws IOException {

			//Fetch through HTTP
			HttpsURLConnection urlConnection = (HttpsURLConnection)remoteUrl.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("User-agent", "Mozilla/4.0");
            urlConnection.setInstanceFollowRedirects(false);
            
			String redirUrl = urlConnection.getHeaderField("Location");
			InputStream stream;
			if (redirUrl != null) {
				URL actualUrl = new URL(redirUrl);
				URLConnection actualConn = actualUrl.openConnection();
				stream = actualConn.getInputStream();
			} else {
				stream = urlConnection.getInputStream();
			}
			
			//Read
			ByteArrayOutputStream buffer = new ByteArrayOutputStream();
			int nRead = 0;
			byte[] copyBuffer = new byte[COPY_BUFFER_SIZE];
			
			Log.d(TAG,"FILE OUTPUT #");
			while((nRead = stream.read(copyBuffer)) != -1){
				
				//System.out.write(copyBuffer, 0, nRead);
				System.out.println("writeline");
				buffer.write(copyBuffer, 0, nRead);
			}
			
			Log.d(TAG,"# FILE OUTPUT");
			//Finalize
			buffer.flush();
			stream.close();
			
			return buffer.toByteArray();
			
	}
	
	

}
